package cn.longwi.lwse.handler;


import cn.longwi.lwse.domain.RespResult;
import cn.longwi.lwse.domain.ResponseCode;
import cn.longwi.lwse.properties.LicenseProperties;
import cn.longwi.lwse.service.LicenseService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LicenseInterceptor implements HandlerInterceptor {

    @Resource
    private LicenseService licenseService;
    @Resource
    private LicenseProperties licenseProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String clientIp = request.getRemoteAddr();
        clientIp = "0:0:0:0:0:0:0:1".equals(clientIp) ? "127.0.0.1" : clientIp;
        if ("127.0.0.1".equals(clientIp) && !licenseProperties.getValidLocal()) {
            return true;
        }
        if (licenseService.isValidateCurrentDay()){
            return true;
        }
        // 判断是否有授权
        RespResult respResult = licenseService.hasValidLicense();
        if (respResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            response.sendRedirect("/license");
            return false;
        }
        return true;
    }


}
